package com.lzx.adx.report.support.strategy.v3.channel;

import cn.hutool.core.util.URLUtil;
import cn.hutool.crypto.SecureUtil;
import cn.hutool.http.HttpUtil;
import com.lzx.adx.report.annnotions.ProductType;
import com.lzx.adx.report.constant.ProductChannelConstant;
import com.lzx.adx.report.dto.AccountDTO;
import com.lzx.adx.report.dto.OcpxAccountDTO;
import com.lzx.adx.report.dto.ProductConfigDTO;
import com.lzx.adx.report.dto.ReportDTO;
import com.lzx.adx.report.support.strategy.v2.channel.AbstractReport;
import com.lzx.adx.report.util.URLEncoderDecoderTool;
import com.lzx.adx.report.util.UrlUtil;
import lombok.extern.slf4j.Slf4j;
import org.apache.commons.lang3.StringUtils;
import org.springframework.stereotype.Component;

import java.nio.charset.StandardCharsets;
import java.util.LinkedHashMap;
import java.util.Map;

@Component
@Slf4j
@ProductType(ProductChannelConstant.JDJR)
public class JdjrReport extends AbstractProductReport {

    @Override
    public String execute(ReportDTO reportDTO, OcpxAccountDTO ocpxAccountDTO, ProductConfigDTO productConfigDTO) {
        long time = System.currentTimeMillis();
        Map<String,String> map=new LinkedHashMap<>();

        map.put("platform","android");
        map.put("ts_ms",String.valueOf(time));
        map.put("click_id",reportDTO.getBizRequestId());
        map.put("ip", reportDTO.getIp());
        map.put("oaid",reportDTO.getOaid());

        if(StringUtils.isNotBlank(reportDTO.getOaid())) {
            map.put("oaid_sum", SecureUtil.md5(reportDTO.getOaid()));
        }
        map.put("android_id_sum","");

        if(StringUtils.isNotBlank(reportDTO.getUser_agent())) {
            map.put("ua", URLEncoderDecoderTool.encodeURL(reportDTO.getUser_agent()));
        }

        String allCabackUrl = String.format(productConfigDTO.getCallbackUrl(), reportDTO.getBizRequestId());
        map.put("callback_url",allCabackUrl);

        String params = URLUtil.buildQuery(map, StandardCharsets.UTF_8);

        String finalUrl = ocpxAccountDTO.getReportUrl() + "&" + params;

        log.info("账号为{},请求产品端的完整地址为 {}", ocpxAccountDTO.getId(), finalUrl);
        String body = HttpUtil.createGet(finalUrl).execute().body();
        log.info("账号为{} 请求产品端，响应的结果为{}", ocpxAccountDTO.getId(), body);

        ocpxAccountDTO.setFinalURL(finalUrl);
        return body;
    }
}
